import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_app/home/entity/User.dart';
import 'package:http/http.dart' as http;

class NetWorkPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _NetWorkPage();
  }
}

class _NetWorkPage extends State<NetWorkPage> {
  MyUser user;
  TextEditingController controller = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("网络操作"),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                  child: CircleAvatar(
                    radius: 36.0,
                    backgroundImage:NetworkImage((user != null && user.avatar_url != null)
                    ? user.avatar_url
                    : "https://avatars2.githubusercontent.com/u/13781886?s=400&u=27f791017d2d2e56b334b096d6b055ac66a4153a&v=4")
                  ),
                margin: EdgeInsets.only(top: 30),
              ),
              ListTile(
                leading: Icon(Icons.person),
                title: Text("name:" +
                    (user != null && user.name != null ? user.name : "暂无")),
              ),
              ListTile(
                leading: Icon(Icons.location_city),
                title: Text("location:" +
                    (user != null && user.location != null
                        ? user.location
                        : "暂无")),
              ),
              ListTile(
                  leading: Icon(Icons.web),
                  title: Text("blog:" +
                      (user != null && user.blog != null ? user.blog : "暂无"))),
              ListTile(
                leading: Icon(Icons.http),
                title: Text("html_url:" +
                    (user != null && user.html_url != null
                        ? user.html_url
                        : "暂无")),
              ),
              TextField(
                decoration: InputDecoration(labelText: "请输入你的github用户名"),
                controller: controller,
              ),
              RaisedButton(
                onPressed: () {
                  getUserInfo(controller.text.toString());
                },
                child: Text("Get请求"),
              ),
            ],
          ),
        ));
  }

  void getUserInfo(String userName) {
    print("请求开始");
    http.get("https://api.github.com/users/$userName").then((response) {
      setState(() {
        final responseJson = json.decode(response.body);
        user = new MyUser.fromJson(responseJson);
        print(user.avatar_url);
      });
    }).catchError((error) {
      print("请求出错：" + error.toString());
    }).whenComplete(() {
      print("请求完成");
    });
  }

}
